<template>
  <div class="page-form">
    <div class="form-wrapper center">
      <div class="form">
        <el-form ref="feeForm" inline>
          <div class="block">
            <div class="title-bar">
              <div class="title"><h2>收款信息</h2></div>
              <div class="op">
                <el-button size="mini" type="text" @click="">保存</el-button>
              </div>
            </div>
            <div class="content">
              <el-row :gutter="layout.colGutter">
                <el-col :span="layout.colSpan">
                  <el-form-item label="现付金额" prop="spotPayFee">
                    <ad-input-number v-model="form.spotPayFee" append="元" :precision="2"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

    </div>
    <div class="op fix-bottom">
      <div class="center">
        <el-button type="primary" :loading="saving" @click="save({redirect: '/order/all'})">保 存</el-button>
        <!--        <el-button type="primary" plain @click="cancel">取 消</el-button>-->
      </div>
    </div>

    <el-dialog title="添加客户" :visible.sync="settlementAdder.visible" custom-class="ad-dialog" width="500px">
      <settlement-adder :mode="settlementAdder.mode" id="" :visible.sync="settlementAdder.visible"/>
    </el-dialog>
  </div>
</template>

<script>
import AdSuggestion from '@/components/AdSuggestion'
import AdInputNumber from '@/components/AdInputNumber'
import AdSelect from '@/components/AdSelect'
import AdCitySelect from '@/components/AdCitySelect'
import AdStatusSelect from '@/components/AdStatusSelect'
import settlementAdder from '@/views/dialog/settlementAdder'
import adPageForm from '@/mixins/adPageForm'
import { getCompanyList as getSuggestCompanyList, getCompanyLineList as getSuggestCompanyLineList, getLinePrice } from '@/api/suggestion'
import { get as getAreaData } from '@/api/city/area'
import { add, edit, getDetail as get } from '@/api/order/all'

class FormCar {
  carName = undefined  // 车辆名称
  vin = undefined  // 车架号
  carCost = undefined  // 车辆单价
  insuranceFee = undefined  // 保险费
  kickbackFee = undefined  // 商务费

  paymentType = []         // 付款方式
  spotPayFee = undefined  // 现付
  deliveryPayFee = undefined  // 到付
  backPayFee = undefined  // 欠付
  slotPayFee = undefined  // 月结
}

class Form {
  origin = 2
  type = undefined  // 客户类型
  companyId = undefined
  companyName = undefined  // 企业名称
  customerLineId = undefined
  customerLineName = undefined  // 线路名称
  startCode = undefined  // 出发地
  destinationCode = undefined  // 目的地
  customerLinkmanId = undefined
  senderName = undefined  // 发货人
  senderPhone = undefined  // 发货电话
  consigneeName = undefined  // 收货人
  consigneePhone = undefined  // 收货电话
  pickType = undefined  // 提车方式
  pickLinkmanName = undefined  // 联系人
  pickLinkmanPhone = undefined  // 联系电话
  senderAddress = undefined  // 提车地址
  takeCarType = undefined  // 送车方式
  consigneeAddress = undefined  // 送车地址

  transportFee = undefined  // 运输费
  pickCarFee = undefined  // 提车费
  takeCarFee = undefined  // 送车费
  carNum = 1          // 车辆数量
  discountFee = undefined  // 优惠金额
  invoiceFee = undefined  // 税额
  orderSubList = [ new FormCar() ]

  paymentType = []         // 付款方式
  spotPayFee = undefined  // 现付
  deliveryPayFee = undefined  // 到付
  backPayFee = undefined  // 欠付
  slotPayFee = undefined  // 月结

  hasUrgent = 0          // 是否加急
  pickCarTime = undefined  // 预约提车时间
  remark = undefined  // 备注
}

export default {
  components: { AdSuggestion, AdInputNumber, AdSelect, AdCitySelect, AdStatusSelect, settlementAdder },
  mixins: [adPageForm({add, edit, get})],
  dicts: ['pickcar_type','takecar_type','payment_type','yes_or_no'],
  data() {
    return {
      layout: { colGutter: 28, colSpan: 6, rowGutter: 16 },
      pickAreaData: [],
      takeAreaData: [],
      suggestedCustomerLineList: [],
      carNum: 1,
      nature: false,
      form: new Form(),
      settlementAdder: {
        visible: false,
        mode: ''
      }
    }
  },
  computed: {
    totalPrice: {
      get() {
        let insuranceFee = 0
        // let kickbackFee = 0
        this.form.orderSubList.forEach(car => {
          insuranceFee += Number(car.insuranceFee || 0)
          // kickbackFee += Number(car.kickbackFee || 0)
        })
        const totalPrice =
          Number(this.form.transportFee || 0) * this.form.orderSubList.length + insuranceFee + // * Number(this.form.carNum || 0) +
          Number(this.form.kickbackFee || 0) + Number(this.form.invoiceFee || 0) + // - Number(this.form.discountFee || 0) +
          Number(this.form.pickFee || 0) + Number(this.form.takeFee || 0) // + insuranceFee + kickbackFee
        this.form.totalFee = totalPrice
        return totalPrice
      },
      set() {}
    }
  },
  watch: {
    form: {
      immediate: true,
      deep: true,
      handler(form) {
        this.selectPaymentType()
        this.autoCompleteForOnlyOnePaymentType()
      }
    },
    'form.startCode': {
      immediate: true,
      handler(code) {
        this.setPickArea()
      }
    },
    'form.destinationCode': {
      immediate: true,
      handler(code) {
        this.setTakeArea()
      }
    }
  },
  methods: { getSuggestCompanyList,
    beforeSave() {
      const acc = Number(this.form.spotPayFee || 0) + Number(this.form.deliveryPayFee || 0) + Number(this.form.backPayFee || 0) + Number(this.form.slotPayFee || 0)
      if (acc != this.totalPrice) {
        this.$notify.error({
          title: '付款方式与合计费用不符合业务要求，请核实后重新输入',
          duration: 5000
        })
        return false
      } else {
        return true
      }
    },
    selectLink(link) {
      this.setLink(link)
      this.setPick()
    },
    removeLink() {
      this.form.companyId = ''
      this.form.companyName = ''
      this.form.linkmanId = ''
      this.form.linkmanName = ''
      this.form.linkmanPhone = undefined
      this.form.pickLinkmanName = ''
      this.form.pickLinkmanPhone = undefined
      this.nature = false
      this.suggestedCustomerLineList = []
    },
    setLink(link) {
      this.form.companyId = link.companyId
      this.form.companyName = link.companyName
      this.form.linkmanId = link.linkmanId
      this.form.linkmanName = link.linkmanName
      this.form.linkmanPhone = link.linkmanPhone
      this.nature = link.nature
      getSuggestCompanyLineList(this.form.companyId).then(res => this.suggestedCustomerLineList = res.data)
    },
    selectSuggestedCustomerLine(line) {
      this.form.startCode = line.startCode
      this.form.destinationCode = line.destinationCode
      this.form.transportFee = line.transportFee
      this.form.orderSubList.map(car => {
        car.carName = line.carType
        return car
      })
    },
    selectPickType() {
      this.setPick()
      this.setPickArea()
    },
    setPick() {
      if (this.form.pickType && this.form.pickType == 3) {
        this.form.pickLinkmanName = ''
        this.form.pickLinkmanPhone = undefined
        this.form.pickAddress = ''
      } else {
        this.form.pickLinkmanName = this.form.linkmanName
        this.form.pickLinkmanPhone = this.form.linkmanPhone
      }
    },
    setPickArea() {
      if (this.form.pickType && this.form.pickType == 3) {
        if (this.form.pickAreaCode) this.form.pickAreaCode = ''
        this.pickAreaData = []
      } else if (this.form.pickType && this.form.startCode) {
        // const code = this.form.startCode.slice(0, 4) + '00'
        const code = this.form.startCode
        getAreaData(code).then(res => {
          this.pickAreaData = res.data
        })
      }
    },
    selectTakeType() {
      this.setTake()
      this.setTakeArea()
    },
    setTake() {
      if (this.form.takeType && this.form.takeType == 3) {
        this.form.takeAddress = ''
      }
    },
    setTakeArea() {
      if (this.form.takeType && (this.form.takeType == 3 || this.form.takeType == 4)) {
        if (this.form.takeAreaCode) this.form.takeAreaCode = ''
        this.takeAreaData = []
      } else if (this.form.takeType && this.form.destinationCode) {
        // const code = this.form.destinationCode.slice(0, 4) + '00'
        const code = this.form.destinationCode
        getAreaData(code).then(res => {
          this.takeAreaData = res.data
        })
      }
    },
    selectCity(city) {
      this.form.customerLineId = undefined
      if (this.form.startCode && this.form.destinationCode) {
        getLinePrice({startCode: this.form.startCode, destinationCode: this.form.destinationCode}).then(res => {
          this.form.transportFee = res.data.totalFee
        })
      } else {
        this.form.transportFee = ''
      }
    },
    changeCarNum() {
      // const cars = new Array(this.form.carNum)
      // this.form.orderSubVOList = cars.fill(new FormCar())
      if (this.carNum > this.form.orderSubList.length) {
        const count = this.carNum - this.form.orderSubList.length
        for (let n = 0; n < count; n++) {
          this.form.orderSubList.push(new FormCar())
        }
      } else if (this.carNum < this.form.orderSubList.length) {
        this.form.orderSubList.splice(this.carNum, this.form.orderSubList.length - 1)
      }
    },
    delCar(index) {
      this.form.orderSubList.splice(index, 1)
      this.carNum = this.form.orderSubList.length
    },
    selectPaymentType() {
      this.autoCompleteForOnlyOnePaymentType()
    },
    autoCompleteForOnlyOnePaymentType() {
      // 清空未选中字段
      if (!(this.form.paymentType.includes(1) || this.form.paymentType.includes('1'))) { // 没现付
        this.form.spotPayFee = undefined
      } else if (!(this.form.paymentType.includes(2) || this.form.paymentType.includes('2'))) { // 没到付
        this.form.deliveryPayFee = undefined
      } else if (!(this.form.paymentType.includes(3) || this.form.paymentType.includes('3'))) { // 没欠付
        this.form.backPayFee = undefined
      } else if (!(this.form.paymentType.includes(4) || this.form.paymentType.includes('4'))) { // 没月付
        this.form.slotPayFee = undefined
      }
      // 付款方式只有一项时直接，直接赋值应收运费合计
      if (this.form.paymentType.length == 1) {
        if (this.form.paymentType.filter(type => type == 1).length > 0) {
          this.form.spotPayFee = this.totalPrice // 现付
        } else if (this.form.paymentType.filter(type => type == 2).length > 0) {
          this.form.deliveryPayFee = this.totalPrice // 到付
        } else if (this.form.paymentType.filter(type => type == 3).length > 0) {
          this.form.backPayFee = this.totalPrice // 欠付
        } else if (this.form.paymentType.filter(type => type == 4).length > 0) {
          this.form.slotPayFee = this.totalPrice // 月付
        }
      }
    },
    openSettlementAdder(mode) {
      this.settlementAdder.visible = true
      if (mode == 'edit') {
        this.settlementAdder.mode = mode
      } else {
        this.settlementAdder.mode = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.center { width: 1300px; }
::v-deep .car-num .el-input__inner { text-align: center; }
.page-form { display: flex; flex: 1; background: #eee; flex-direction: column; align-items: center;
  h1 { margin: 15px 0; text-align: center; font-size: 24px; font-weight: bold; }
  // 背景多图 https://www.cnblogs.com/xiaolantian/p/12629076.html
  .form-wrapper { margin-top: 24px; margin-bottom: 80px; background-color: #fff; background-image: linear-gradient(to right, #5EB9FF 25%, #DEDEDE 25%, #DEDEDE 50%, #5694B7 50%, #5694B7 75%, #DEDEDE 25%); background-size: 80px 2px;  background-repeat: repeat-x;
    .form { margin-bottom: 25px; padding: 26px 24px 0;
      .title-bar { display: flex; height: 40px; border-bottom: 1px solid #85AFD6; background: #F3F3F3; align-items: center;
        .title { display: flex; margin: 0 auto 0 24px; align-items: center;
          h2 { font-size: 14px; font-weight: bold; }
          i { font-size: 14px; color: #979797; font-style: inherit;
            &.required { color: red; }}}
        .op { margin-right: 24px;
          .el-button { font-weight: normal; }
          .item { display: flex; align-items: center;
            .label { font-size: 14px; color: #303030; }}}}
      .total-bar { height: 50px; line-height: 50px; font-size: 14px;
        .label { margin-left: 24px; font-size: 16px; font-weight: bold;
          i { margin-right: 4px; font-style: normal; color: #EC2D0F; }}
        .tip { margin-left: 6px; font-size: 12px; color: #888; }}
      .block { padding-bottom: 10px; border: 1px solid #DCDCDC;
        &+.block { margin-top: 24px; }
        .content { padding: 24px 24px 0;
          .el-form-item { display: flex; }}}}}}
</style>